package com.fengwk.support.fetch;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.HttpClientUtils;
import com.fengwk.support.util.IoUtils;
import com.fengwk.support.util.JsonUtils;
import com.fengwk.support.util.StringUtils;
import com.fengwk.support.util.HttpClientUtils.ResponseEntity;

/**
 * https://max.book118.com
 * 
 * 抓取book118图片文档
 */
public class Book118Fetchs {
	
	private Book118Fetchs() {
		throw new BaseException("can not install " + Book118Fetchs.class);
	}
	
	/**
	 * 抓取pdf类型文档的图片
	 * 
	 * @param outDir 输出目录
	 * @param fistIndex 首图片的序号,接下来的图片按加1排列
	 * @param viewNum 抓取地址:viewNum
	 * @param firstImg 抓取参数:首页面图片
	 * @param f 抓取参数
	 * @param readLimit 抓取参数
	 * @param furl 抓取参数
	 */
	public static void image(String outDir, int fistIndex, int viewNum, String firstImg, String f, String readLimit, String furl) {
		Map<String, String> params = new HashMap<>();
		params.put("f", f);
		params.put("img", firstImg);
		params.put("isMobile", "false");
		params.put("isNet", "true");
		params.put("readLimit", readLimit);
		params.put("furl", furl);
		ResponseEntity responseEntity = HttpClientUtils.get("https://view" + viewNum + ".book118.com/pdf/GetNextPage/", params, null);
		String res = responseEntity.getStringContent();
		@SuppressWarnings("unchecked")
		Map<String, Object> map = JsonUtils.fromJson(res, Map.class);
		String next = (String) map.get("NextPage");
		if (StringUtils.isBlank(next) || "ReadLimit".equals(next)) {
			return;
		}
		image(outDir, fistIndex + 1, viewNum, next, f, readLimit, furl);
		responseEntity = HttpClientUtils.get("https://view" + viewNum + ".book118.com/img/?img=" + next, null, null);
		byte[] bytes = responseEntity.getContent();
		IoUtils.write(bytes, outDir + File.separator + fistIndex + ".png");
	}
	
	public static void main(String[] args) throws IOException {
		image(
				"D:/抓取",
				1,
				57, 
				"Hs92T42xAvuq4rofpzGS@G@D5QaEQTVm0Ad5lQqfchyHHBNIl1Ape4osOPu5rItX", 
				"dXAxMy5ib29rMTE4LmNvbS44MFwxNzkzMDczLTU2ZTFiODZhMzQ4Y2IucGRm", 
				"9nrFEu488918C3iasP5sNA==", 
				"YOQStEpojXCuhBxIw8SKYDQWBUE_xGC937OnGWova_VtPt@m63dl8S9er6dXNX2zsRUIepyNos79b7ZwvnGo6DDPLmugo8CCRetuNN81EI0=");
	}
	
}
